import React, { useReducer, useState } from 'react';

// 定义状态类型
interface Todo {
  id: number;
  text: string;
  completed: boolean;
  priority: 'low' | 'medium' | 'high';
}

interface TodoState {
  todos: Todo[];
  filter: 'all' | 'active' | 'completed';
  searchTerm: string;
}

// 定义action类型
type TodoAction =
  | { type: 'ADD_TODO'; text: string; priority: 'low' | 'medium' | 'high' }
  | { type: 'TOGGLE_TODO'; id: number }
  | { type: 'DELETE_TODO'; id: number }
  | { type: 'SET_FILTER'; filter: 'all' | 'active' | 'completed' }
  | { type: 'SET_SEARCH_TERM'; searchTerm: string }
  | { type: 'CLEAR_COMPLETED' }
  | { type: 'TOGGLE_ALL' };

// 初始状态
const initialState: TodoState = {
  todos: [
    { id: 1, text: '学习React', completed: false, priority: 'high' },
    { id: 2, text: '学习TypeScript', completed: true, priority: 'medium' },
    { id: 3, text: '构建项目', completed: false, priority: 'low' }
  ],
  filter: 'all',
  searchTerm: ''
};

// Reducer函数
const todoReducer = (state: TodoState, action: TodoAction): TodoState => {
  switch (action.type) {
    case 'ADD_TODO':
      const newTodo: Todo = {
        id: Date.now(),
        text: action.text,
        completed: false,
        priority: action.priority
      };
      return {
        ...state,
        todos: [...state.todos, newTodo]
      };

    case 'TOGGLE_TODO':
      return {
        ...state,
        todos: state.todos.map(todo =>
          todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
        )
      };

    case 'DELETE_TODO':
      return {
        ...state,
        todos: state.todos.filter(todo => todo.id !== action.id)
      };

    case 'SET_FILTER':
      return {
        ...state,
        filter: action.filter
      };

    case 'SET_SEARCH_TERM':
      return {
        ...state,
        searchTerm: action.searchTerm
      };

    case 'CLEAR_COMPLETED':
      return {
        ...state,
        todos: state.todos.filter(todo => !todo.completed)
      };

    case 'TOGGLE_ALL':
      const allCompleted = state.todos.every(todo => todo.completed);
      return {
        ...state,
        todos: state.todos.map(todo => ({
          ...todo,
          completed: !allCompleted
        }))
      };

    default:
      return state;
  }
};

// 复杂计数器reducer
interface CounterState {
  count: number;
  history: number[];
  step: number;
}

type CounterAction =
  | { type: 'INCREMENT' }
  | { type: 'DECREMENT' }
  | { type: 'RESET' }
  | { type: 'SET_STEP'; step: number }
  | { type: 'UNDO' };

const counterReducer = (state: CounterState, action: CounterAction): CounterState => {
  switch (action.type) {
    case 'INCREMENT':
      const newCount = state.count + state.step;
      return {
        ...state,
        count: newCount,
        history: [...state.history, newCount]
      };

    case 'DECREMENT':
      const decCount = state.count - state.step;
      return {
        ...state,
        count: decCount,
        history: [...state.history, decCount]
      };

    case 'RESET':
      return {
        ...state,
        count: 0,
        history: [...state.history, 0]
      };

    case 'SET_STEP':
      return {
        ...state,
        step: action.step
      };

    case 'UNDO':
      if (state.history.length <= 1) return state;
      const newHistory = state.history.slice(0, -1);
      return {
        ...state,
        count: newHistory[newHistory.length - 1] || 0,
        history: newHistory
      };

    default:
      return state;
  }
};

const UseReducerDemo: React.FC = () => {
  const [todoState, todoDispatch] = useReducer(todoReducer, initialState);
  const [counterState, counterDispatch] = useReducer(counterReducer, {
    count: 0,
    history: [0],
    step: 1
  });

  const [newTodoText, setNewTodoText] = useState('');
  const [priority, setPriority] = useState<'low' | 'medium' | 'high'>('medium');

  // 过滤待办事项
  const filteredTodos = todoState.todos
    .filter(todo => {
      switch (todoState.filter) {
        case 'active':
          return !todo.completed;
        case 'completed':
          return todo.completed;
        default:
          return true;
      }
    })
    .filter(todo => 
      todo.text.toLowerCase().includes(todoState.searchTerm.toLowerCase())
    );

  const addTodo = () => {
    if (newTodoText.trim()) {
      todoDispatch({ type: 'ADD_TODO', text: newTodoText, priority });
      setNewTodoText('');
    }
  };

  const getPriorityColor = (priority: 'low' | 'medium' | 'high') => {
    switch (priority) {
      case 'high': return '#ff4444';
      case 'medium': return '#ffaa00';
      case 'low': return '#00aa00';
    }
  };

  return (
    <div className="demo-page">
      <h1>useReducer Hook 演示</h1>
      <p className="description">
        useReducer是useState的替代方案，适用于复杂的状态逻辑。
      </p>

      {/* 复杂计数器示例 */}
      <section className="demo-section">
        <h2>1. 复杂计数器（带历史记录）</h2>
        <div className="counter-demo">
          <div className="counter-controls">
            <div className="step-control">
              <label>步长: </label>
              <input
                type="number"
                value={counterState.step}
                onChange={(e) => counterDispatch({ 
                  type: 'SET_STEP', 
                  step: parseInt(e.target.value) || 1 
                })}
                min="1"
                max="10"
              />
            </div>
            
            <div className="counter-display">
              <h3>当前值: {counterState.count}</h3>
              <div className="button-group">
                <button onClick={() => counterDispatch({ type: 'INCREMENT' })}>
                  +{counterState.step}
                </button>
                <button onClick={() => counterDispatch({ type: 'DECREMENT' })}>
                  -{counterState.step}
                </button>
                <button onClick={() => counterDispatch({ type: 'RESET' })}>
                  重置
                </button>
                <button 
                  onClick={() => counterDispatch({ type: 'UNDO' })}
                  disabled={counterState.history.length <= 1}
                >
                  撤销
                </button>
              </div>
            </div>
            
            <div className="history">
              <h4>历史记录:</h4>
              <div className="history-list">
                {counterState.history.slice(-5).map((value, index) => (
                  <span 
                    key={index} 
                    className={index === counterState.history.slice(-5).length - 1 ? 'current' : ''}
                  >
                    {value}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* 待办事项应用 */}
      <section className="demo-section">
        <h2>2. 待办事项应用</h2>
        <div className="todo-app">
          {/* 添加新待办 */}
          <div className="add-todo">
            <input
              type="text"
              value={newTodoText}
              onChange={(e) => setNewTodoText(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && addTodo()}
              placeholder="添加新的待办事项..."
            />
            <select
              value={priority}
              onChange={(e) => setPriority(e.target.value as 'low' | 'medium' | 'high')}
            >
              <option value="low">低优先级</option>
              <option value="medium">中优先级</option>
              <option value="high">高优先级</option>
            </select>
            <button onClick={addTodo}>添加</button>
          </div>

          {/* 过滤和搜索 */}
          <div className="filters">
            <div className="filter-buttons">
              <button
                className={todoState.filter === 'all' ? 'active' : ''}
                onClick={() => todoDispatch({ type: 'SET_FILTER', filter: 'all' })}
              >
                全部 ({todoState.todos.length})
              </button>
              <button
                className={todoState.filter === 'active' ? 'active' : ''}
                onClick={() => todoDispatch({ type: 'SET_FILTER', filter: 'active' })}
              >
                未完成 ({todoState.todos.filter(t => !t.completed).length})
              </button>
              <button
                className={todoState.filter === 'completed' ? 'active' : ''}
                onClick={() => todoDispatch({ type: 'SET_FILTER', filter: 'completed' })}
              >
                已完成 ({todoState.todos.filter(t => t.completed).length})
              </button>
            </div>
            
            <input
              type="text"
              placeholder="搜索..."
              value={todoState.searchTerm}
              onChange={(e) => todoDispatch({ 
                type: 'SET_SEARCH_TERM', 
                searchTerm: e.target.value 
              })}
            />
          </div>

          {/* 待办列表 */}
          <div className="todo-list">
            {filteredTodos.map(todo => (
              <div key={todo.id} className="todo-item">
                <input
                  type="checkbox"
                  checked={todo.completed}
                  onChange={() => todoDispatch({ type: 'TOGGLE_TODO', id: todo.id })}
                />
                <span 
                  className={`todo-text ${todo.completed ? 'completed' : ''}`}
                  style={{ color: getPriorityColor(todo.priority) }}
                >
                  {todo.text}
                </span>
                <span className="priority-badge" style={{ backgroundColor: getPriorityColor(todo.priority) }}>
                  {todo.priority}
                </span>
                <button
                  onClick={() => todoDispatch({ type: 'DELETE_TODO', id: todo.id })}
                >
                  删除
                </button>
              </div>
            ))}
          </div>

          {todoState.todos.some(todo => todo.completed) && (
            <button
              onClick={() => todoDispatch({ type: 'CLEAR_COMPLETED' })}
              className="clear-completed"
            >
              清除已完成
            </button>
          )}

          <button
            onClick={() => todoDispatch({ type: 'TOGGLE_ALL' })}
            className="toggle-all"
          >
            全选/取消全选
          </button>
        </div>
      </section>

      {/* 使用要点 */}
      <section className="demo-section">
        <h2>3. useReducer vs useState</h2>
        <div className="comparison">
          <div className="comparison-item">
            <h3>useState适用场景</h3>
            <ul>
              <li>简单的状态管理</li>
              <li>状态之间关联性不强</li>
              <li>状态更新逻辑简单</li>
            </ul>
          </div>
          
          <div className="comparison-item">
            <h3>useReducer适用场景</h3>
            <ul>
              <li>复杂的状态逻辑</li>
              <li>多个子状态相互依赖</li>
              <li>状态更新逻辑复杂</li>
              <li>需要可预测的状态更新</li>
            </ul>
          </div>
        </div>
      </section>

      {/* 代码示例 */}
      <section className="demo-section">
        <h2>4. 代码示例</h2>
        <div className="code-example">
          <h3>基本语法:</h3>
          <pre>
{`const [state, dispatch] = useReducer(reducer, initialState);

// reducer函数
function reducer(state, action) {
  switch (action.type) {
    case 'ACTION_TYPE':
      return { ...state, /* 更新状态 */ };
    default:
      return state;
  }
}

// 使用dispatch
dispatch({ type: 'ACTION_TYPE', payload: data });`}
          </pre>

          <h3>复杂状态示例:</h3>
          <pre>
{`// 状态结构
const state = {
  users: [],
  loading: false,
  error: null,
  filters: { search: '', sort: 'name' }
};

// action类型
const actions = {
  FETCH_START: 'FETCH_START',
  FETCH_SUCCESS: 'FETCH_SUCCESS',
  FETCH_ERROR: 'FETCH_ERROR',
  UPDATE_FILTERS: 'UPDATE_FILTERS'
};`}
          </pre>
        </div>
      </section>
    </div>
  );
};

export default UseReducerDemo;